# Copyright 2018 Maco
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
from hashlib import sha256


def hash_block(block):
    '''
    生成块的SHA-256 hash值
    :param data: dict object.
    :return: <str>
    '''
    string = str(block['prev_hash']) + \
        str(block['index']) + str(block['tx_count']) + str(block['proof'])
    return hash_str(string)


def hash_dict(data):
    '''
    生成交易的SHA-256 hash值
    :param data: dict object.
    :return: <str>
    '''
    string = json.dumps(data, sort_keys=True).encode()
    return sha256(string).hexdigest()


def hash_str(string):
    '''
    计算字符串的hash值
    :param string: <str> 字符串
    :return: <str>
    '''
    if isinstance(string, str):
        string = string.encode()
    return sha256(string).hexdigest()
